<script lang="ts">
  import Time, { svelteTime } from "svelte-time";

  import { actixGraphqlEndpoint } from "$lib/js/stores";
  import { page } from "$app/stores";
  import { request, gql } from "graphql-request";

  import { useQuery, useMutation } from "@sveltestack/svelte-query";

  import VPlayer from "$lib/player/VPlayer.svelte";
  import type { Quiz, QuizItem, KV, Nodedge } from "$lib/ebm";
  let quizid = $page.params.quizid;

  let endpoint = $actixGraphqlEndpoint;
  const FIND_QUIZ_QUERY = gql`
        query {
            node(id: "${quizid}") {
                id
                createdAt
                updatedAt
                ... on Quiz {
                    seq
                    level
                    subject
                    title
                    m3U8
                    description
                    myEbpInfo{
                      userId
                      quizId
                      ebpAt
                    }
                    quizItems {
                        id
                        title
                        description
                        m3U8
                        isMaster
                        masterId
                        options{k v}
                        master{
                          id
                          title
                          description
                        }
                    }
                }
            }
        }
    `;

  const findQuizResult = useQuery<Quiz, { message: string }>(
    ["quiz", $page.params.quizid],
    async () => {
      const { node } = await request(endpoint, FIND_QUIZ_QUERY);
      return node;
    },
    {
      enabled: !!$page.params.quizid,
    }
  );

  const ADD_EBP_QUIZ_MUTATION = gql`
      mutation 
      { nodege: addEbpQuiz(input: { id: "${quizid}" }) 
        {     
          id
          createdAt
          updatedAt
          ... on Quiz {
                    seq
                    level
                    subject
                    title
                    description
                    myEbpInfo{
                      userId
                      quizId
                      ebpAt
                    }
          }
        } 
      }
  `;

  const mutation = useMutation<Nodedge, { message: string }>(async () => {
    const { nodege } = await request(endpoint, ADD_EBP_QUIZ_MUTATION);
    return nodege;
  });
</script>

<div class="w-full flex flex-col items-center justify-center p-4 bg-gray-300">
  {#if $findQuizResult.isLoading}
    <p>Loading...</p>
  {:else if $findQuizResult.isError}
    <p>Error {$findQuizResult.error}</p>
  {:else}
    <h1>{$findQuizResult.data.title}({$findQuizResult.data.id})</h1>

    <div class="flex flex-wrap bg-purple-500 justify-items-center w-full m-4">
      <VPlayer
        attributes={[
          {
            k: "poster",
            v: "https://media.vimejs.com/poster.png",
          },
          {
            k: "data_src",
            v: $findQuizResult.data.m3U8,
          },
        ]}
      />
    </div>

    <p>
      {$findQuizResult.data.description}
    </p>
    <div class="w-full mt-6 mb-6 items-center justify-center ">
      {#if $findQuizResult.data.myEbpInfo && $findQuizResult.data.myEbpInfo.ebpAt}
        <label
          class="bg-gray-400 flex my-2 text-base rounded-md hover:border-gray-500 border-gray-300 px-6 py-3 border-2 bg-gray-100 uppercase"
          for="0q0"
        >
          Added to My EBP&nbsp;
          <Time
            relative
            timestamp={new Date($findQuizResult.data.myEbpInfo.ebpAt * 1000)}
          />
        </label>
      {:else if $mutation.isLoading}
        <p>Adding Quiz To EBP ...</p>
      {:else if $mutation.isError}
        <div>An error occurred: {$mutation.error.message}</div>
      {:else if $mutation.isSuccess}
        <label
          class="bg-rose-400 flex my-2 text-base rounded-md hover:border-gray-500 border-gray-300 px-6 py-3 border-2 bg-gray-100 uppercase"
          for="0q0"
        >
          Added to My EBP Successfully!
        </label>
      {:else}
        <button
          on:click={() => {
            console.log("calling mutate()");
            $mutation.mutate();
          }}
          class="w-full block px-3 py-2 font-semibold text-center text-white transition-colors duration-200 transform bg-blue-500 rounded-md hover:bg-blue-400 uppercase"
        >
          Add To My EBP (Ebbinghaus Programme)
        </button>
      {/if}
    </div>

    <div class="w-full">
      {#each $findQuizResult.data.quizItems as qi, i}
        <div class="w-full mb-8" data-v-788a5fef="">
          <div class=" flex my-auto">
            <span
              class="px-2 m-1 rounded-full bg-black text-gray-100 h-6 w-18 my-auto"
            >
              {i + 1}
            </span>
            <span class="text-left text-lg font-semibold m-1">{qi.title}</span>
          </div>
          <div class="flex my-auto text-left bg-gray-100 p-2">
            {qi.description}
          </div>
          {#each qi.options as option}
            <label
              class="checked:bg-red-600 flex my-2 text-base rounded-md hover:border-gray-500 border-gray-300 px-6 py-3 border-2 bg-gray-100"
              for="0q0"
            >
              {option.k}:{option.v}
            </label>
          {/each}
          <div
            class="bg-red-200 relative text-red-600 py-1 px-3 rounded-lg"
            style="display: none;"
          >
            You did not provide an answer.
          </div>
        </div>
      {/each}
    </div>

    <div class="w-full mt-6 mb-6 items-center justify-center ">
      {#if $findQuizResult.data.myEbpInfo && $findQuizResult.data.myEbpInfo.ebpAt}
        <label
          class="bg-gray-400 flex my-2 text-base rounded-md hover:border-gray-500 border-gray-300 px-6 py-3 border-2 bg-gray-100 uppercase"
          for="0q0"
        >
          Added to My EBP&nbsp;
          <Time
            relative
            timestamp={new Date($findQuizResult.data.myEbpInfo.ebpAt * 1000)}
          />
        </label>
      {:else if $mutation.isLoading}
        <p>Adding Quiz To EBP ...</p>
      {:else if $mutation.isError}
        <div>An error occurred: {$mutation.error.message}</div>
      {:else if $mutation.isSuccess}
        <label
          class="bg-rose-400 flex my-2 text-base rounded-md hover:border-gray-500 border-gray-300 px-6 py-3 border-2 bg-gray-100 uppercase"
          for="0q0"
        >
          Added to My EBP Successfully!
        </label>
      {:else}
        <button
          on:click={() => {
            console.log("calling mutate()");
            $mutation.mutate();
          }}
          class="w-full block px-3 py-2 font-semibold text-center text-white transition-colors duration-200 transform bg-blue-500 rounded-md hover:bg-blue-400 uppercase"
        >
          Add To My EBP (Ebbinghaus Programme)
        </button>
      {/if}
    </div>
    <p>
      {$findQuizResult.data.description}
    </p>
  {/if}

  <p>
    Tailwind components and template collections are fully responsive UI
    components and page templates that allow you to copy and paste HTML snippets
    directly into your codebase to use or modify. Built by other developers and
    organizations, these collections allow you to get started on your project
    quickly by seeing the potential outcome. In this article, I’ll introduce you
    to seven of the best free Tailwind CSS component collections. If you have no
    experience using Tailwind CSS, you may want to read this article on styling
    components with Tailwind CSS first. Let’s dive in. Tailwind components and
    template collections are fully responsive UI components and page templates
    that allow you to copy and paste HTML snippets directly into your codebase
    to use or modify. Built by other developers and organizations, these
    collections allow you to get started on your project quickly by seeing the
    potential outcome. In this article, I’ll introduce you to seven of the best
    free Tailwind CSS component collections. If you have no experience using
    Tailwind CSS, you may want to read this article on styling components with
    Tailwind CSS first. Let’s dive in.
  </p>
</div>
